package com.lhb.SC.oss.web;

import com.lhb.SC.web.context.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    private String filePath = "d:/tmp/upload/file/";

    @RequestMapping("/file")
    public ResponseResult<Object> handleFileUpload(@RequestPart("file") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return ResponseResult.fail("1", "文件为空");
        }
        MultipartFile file = files[0];
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return ResponseResult.success("上传成功");
        } catch (Exception e) {
            log.error("上传失败", e);
            return ResponseResult.fail("1", "文件为空");
        }
    }

}
